<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="form.productName" style="width: 800px;" />
      </el-form-item>

      <el-form-item label="商品副标题" prop="productInfo">
        <el-input v-model="form.productInfo" style="width: 800px;" rows="2" type="textarea" />
      </el-form-item>

      <el-form-item label="商品分类" prop="cateId">
        <treeselect v-model="form.cateId" :options="cates" style="width: 300px;" placeholder="选择商品分类" />
      </el-form-item>

      <el-form-item label="商品封面图" prop="imageArr">
        <multi-upload v-model="form.imageArr" :max-count="1" />
      </el-form-item>

      <el-form-item label="商品轮播图" prop="sliderImageArr">
        <multi-upload v-model="form.sliderImageArr" />
      </el-form-item>
      <el-form-item label="商品状态" prop="isShow">
        <el-radio-group v-model="form.isShow">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="定时上架" prop="onSaleTime">
        <el-date-picker
          v-model="form.onSaleTime"
          type="datetime"
          placeholder="选择商品上架时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="expireTimeOption"
        />
      </el-form-item>
      <el-form-item label="定时下架" prop="unOnSaleTime">
        <el-date-picker
          v-model="form.unOnSaleTime"
          type="datetime"
          placeholder="选择商品下架时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="expireTimeOption"
        />
      </el-form-item>
      <el-form-item label="市场价" prop="otPrice">
        <el-input-number v-model="form.otPrice" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="售价" prop="price">
        <el-input-number v-model="form.price" :min="0" :precision="2" />
      </el-form-item>
      <template v-if="memberPrices.length > 0">
        <el-form-item
          v-for="(mp, mpIdx) in memberPrices"
          :key="mp.id"
          :label="mp.memberLevelName + '商品售价'"
          :rules="{
            required: true,
            message: mp.memberLevelName + '商品售价不能为空',
            trigger: 'blur',
          }"
        >
          <el-input-number
            v-model="memberPrices[mpIdx].memberPrice"
            style="width:160px"
            :precision="2"
            :min="0"
          />
        </el-form-item>
      </template>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="form.stock" :min="0" />
      </el-form-item>
      <!--      <el-form-item label="赠送积分" prop="giveIntegral">-->
      <!--        <el-input-number v-model="form.giveIntegral" :min="0" />-->
      <!--      </el-form-item>-->
      <el-form-item label="售卖单位" prop="unitName">
        <el-input v-model="form.unitName" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="商品重量" prop="weight">
        <el-input v-model="form.weight" placeholder="请输入商品重量" style="width: 200px;">
          <template #append>g</template>
        </el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>

      <el-form-item label="运费模板" prop="tempId">
        <el-select v-model="form.tempId" clearable placeholder="请选择">
          <el-option
            v-for="item in shippingTemplates"
            :key="item.transportId"
            :label="item.transName"
            :value="item.transportId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品详情">
        <tinymce :key="tinymceFlag" v-model="form.description" :height="800" :width="1000" />
      </el-form-item>

      <el-form-item>
        <el-button :loading="loading" type="primary" style="width: 100px" @click="resetProductForm">重置</el-button>
        <el-button :loading="loading" type="primary" style="width: 100px" @click="doSubmit">确认发布</el-button>
        <el-button :loading="loading" type="primary" style="width: 100px" @click="saveDrafts">保存草稿</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCates } from '@/api/pms/yxStoreCategory'
import { add } from '@/api/pms/yxStoreProduct'
import Tinymce from '@/components/Tinymce'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MultiUpload from '@/components/Upload/MultiUpload'
import { listTransport } from '@/api/oms/transport'
import { localRead, localRemove, localSave } from '@/utils'
import { listMember_level } from '@/api/ums/member_level'
// import MaterialList from '@/components/material'
export default {
  components: { MultiUpload, Tinymce, Treeselect },
  data() {
    return {
      loading: false, isAdd: true, cates: [], shippingTemplates: [], tinymceFlag: 1,
      goodsId: undefined,
      memberPrices: [],
      form: {
        id: '',
        image: '',
        sliderImage: '',
        imageArr: [],
        sliderImageArr: [],
        productName: '',
        productInfo: '',
        cateId: undefined,
        price: 0,
        vipPrice: 0,
        otPrice: 0,
        unitName: '件',
        weight: '0',
        sort: 0,
        sales: 0,
        stock: 0,
        isShow: 1,
        description: '',
        tempId: undefined,
        giveIntegral: 0,
        memberPrice: [],
        onSaleTime: undefined,
        unOnSaleTime: undefined
      },
      rules: {
        productName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        productInfo: [
          { required: true, message: '商品副标题不能为空', trigger: 'blur' }
        ],
        imageArr: [
          { required: true, message: '请上传商品封面图', trigger: 'blur' }
        ],
        sliderImageArr: [
          { required: true, message: '请上传商品轮播图', trigger: 'blur' }
        ],
        otPrice: [
          { required: true, message: '请填写市场价', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请填写售价', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请填写库存', trigger: 'blur' }
        ],
        tempId: [
          { required: true, message: '请选择运费模板', trigger: 'blur' }
        ],
        cateId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      expireTimeOption: {
        disabledDate(date) {
          // 当天可选：date.getTime() < Date.now() - 24 * 60 * 60 * 1000
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  watch: {
    'form.imageArr': function(val) {
      if (val) {
        this.form.image = val.join(',')
      }
    },
    'form.sliderImageArr': function(val) {
      if (val) {
        this.form.sliderImage = val.join(',')
      }
    },
    isAdd: function(val) {
      if (val) {
        this.$message({
          message: 'add',
          type: 'success'
        })
      }
    }
  },
  async created() {
    this.getCates()
    this.getMemberLevelList()
    this.getShippingTemplate()
    this.initGoodsInfo()
  },
  methods: {
    initGoodsInfo() {
      const isAdd = this.$route.query.isAdd
      if (isAdd !== undefined && isAdd === 'true') {
        this.readProductData()
      }
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.loading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.doAdd()
        } else {
          this.loading = false
        }
      })
    },
    doAdd() {
      this.form.memberPrice = this.memberPrices
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$router.go(-1) // 返回上一层
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetProductForm() {
      this.$confirm('是否重置商品发布信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localRemove('productData')
        this.resetForm()
      }).catch(() => {
      })
    },
    resetForm() {
      this.tinymceFlag++
      this.$refs['form'].resetFields()
      this.form = {
        id: undefined,
        image: '',
        sliderImage: '',
        imageArr: [],
        sliderImageArr: [],
        productName: '',
        productInfo: '',
        cateId: undefined,
        price: 0,
        vipPrice: 0,
        otPrice: 0,
        unitName: '件',
        weight: '0',
        sort: 0,
        sales: 0,
        stock: 0,
        isShow: 1,
        description: '',
        tempId: undefined,
        giveIntegral: 0,
        memberPrice: []
      }
      this.getMemberLevelList()
    },
    saveDrafts() {
      const productData = {
        data: this.form
      }
      localSave('productData', productData)
      this.$message({
        message: '保存草稿成功',
        type: 'success'
      })
    },
    readProductData() {
      const productData = localRead('productData')
      if (productData) {
        this.$confirm('是否读取本地缓存草稿?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form = productData.data
        }).catch(() => {
        })
      }
    },
    getCates() {
      getCates({ enabled: true }).then(res => {
        this.cates = res.data.list
      })
    },
    getMemberLevelList() {
      listMember_level({ queryMode: 'list', status: 1 }).then(res => {
        const memberLevels = res.data
        // 会员价，也必须在循环里面生成，否则会导致数据绑定问题
        const memberPrices = []
        if (memberLevels.length > 0) {
          for (let i = 0; i < memberLevels.length; i++) {
            memberPrices.push({
              memberLevelId: memberLevels[i].id,
              memberLevelName: memberLevels[i].name,
              memberPrice: 0.00
            })
          }
        }
        this.memberPrices = memberPrices
      })
    },
    getShippingTemplate() {
      listTransport().then(res => {
        this.shippingTemplates = res.data
      })
    }
  }
}
</script>

<style scoped>

</style>
